import { AMAP_CONFIG } from '@/config/amap'

// 使用JSONP方式调用高德API避免跨域问题
function jsonpRequest(url, params) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    const callbackName = 'amapCallback_' + Date.now() + '_' + Math.random().toString(36).substr(2);
    
    // 设置全局回调函数
    window[callbackName] = function(data) {
      resolve(data);
      document.head.removeChild(script);
      delete window[callbackName];
    };
    
    // 构建URL
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&');
    
    script.src = `${url}?${queryString}&callback=${callbackName}`;
    script.onerror = () => {
      reject(new Error('JSONP request failed'));
      document.head.removeChild(script);
      delete window[callbackName];
    };
    
    document.head.appendChild(script);
  });
}

// 关键字搜索API
export function searchByKeyword(params) {
  return jsonpRequest('https://restapi.amap.com/v3/place/text', {
    key: AMAP_CONFIG.apiKey,
    keywords: params.keywords,
    city: params.city || '',
    citylimit: true,
    offset: params.offset || 10,
    page: params.page || 1,
    extensions: 'all'
  });
}

// 输入提示API
export function inputTips(params) {
  return jsonpRequest('https://restapi.amap.com/v3/assistant/inputtips', {
    key: AMAP_CONFIG.apiKey,
    keywords: params.keywords,
    city: params.city || '',
    citylimit: true,
    datatype: 'all'
  });
}

// 逆地理编码API
export function getAddressByLocation(lng, lat) {
  return jsonpRequest('https://restapi.amap.com/v3/geocode/regeo', {
    key: AMAP_CONFIG.apiKey,
    location: `${lng},${lat}`,
    poitype: '',
    radius: 1000,
    extensions: 'all',
    batch: false,
    roadlevel: 0
  });
}

// 地理编码API
export function getLocationByAddress(address, city = '') {
  return jsonpRequest('https://restapi.amap.com/v3/geocode/geo', {
    key: AMAP_CONFIG.apiKey,
    address: address,
    city: city,
    batch: false
  });
}

// 生成静态地图URL
export function generateStaticMapUrl(params) {
  const {
    center = '116.397428,39.90923',
    zoom = 13,
    size = '600*400',
    markers = '',
    labels = '',
    paths = '',
    traffic = 0
  } = params

  const baseUrl = 'https://restapi.amap.com/v3/staticmap'
  
  // 构建参数对象，过滤空值
  const queryParams = {
    key: AMAP_CONFIG.apiKey,
    location: center,
    zoom: zoom,
    size: size
    // 移除scale参数，可能导致问题
  }
  
  // 暂时注释掉markers参数，因为API返回错误
  // if (markers) {
  //   // 标记格式：经度,纬度
  //   queryParams.markers = markers;
  // }
  if (labels) {
    queryParams.labels = labels;
  }
  if (paths) {
    queryParams.paths = paths;
  }
  if (traffic) {
    queryParams.traffic = traffic;
  }

  // 手动构建查询字符串，确保格式正确
  const queryString = Object.keys(queryParams)
    .map(key => `${key}=${queryParams[key]}`)
    .join('&');

  const url = `${baseUrl}?${queryString}`;
  console.log('生成的静态地图URL:', url);
  
  return url;
}

// 坐标转换API（如果需要的话）
export function convertCoordinate(locations, coordsys = 'gps') {
  return request({
    url: 'https://restapi.amap.com/v3/assistant/coordinate/convert',
    method: 'get',
    params: {
      key: AMAP_CONFIG.apiKey,
      locations: locations,
      coordsys: coordsys,
      output: 'json'
    }
  })
}